package com.winxuan.channel.support.view.json;

/*
 * @(#)JsonView.java
 *
 * Copyright 2011 Xinhua Online, Inc. All rights reserved.
 */


import java.util.Collection;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.view.AbstractView;

/**
 * description
 * 
 * @author liuan
 * @version 1.0,2011-6-16
 */
class JsonView extends AbstractView {

	private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8";

	private static final Log LOG = LogFactory.getLog(JsonView.class);

	private Collection<Pattern> includeProperties;

	private String jsonTemplateFile;

	private boolean error;

	public JsonView() {
		setContentType(DEFAULT_CONTENT_TYPE);
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (error) {
			LOG.warn("The json template file [" + jsonTemplateFile
					+ "] not found");
			response.setStatus(404);

		} else {
			String jsonString = new JsonWriter().write(model, null,
					includeProperties, false);
			response.setContentType(getContentType());
			response.getWriter().write(jsonString);
		}
	}

	public void setIncludeProperties(Collection<Pattern> includeProperties) {
		this.includeProperties = includeProperties;
	}

	public void setJsonTemplateFile(String jsonTemplateFile) {
		this.jsonTemplateFile = jsonTemplateFile;
	}

	public void setError(boolean error) {
		this.error = error;
	}

}
